package com.gogowan.agroenterprise.base;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: ListView 的通用适配器
 * @author mdp
 * @date 2017年1月3日 上午11:30:35 
 */
public abstract class AbsListAdapter<T> extends BaseAdapter {

    private Context mContext;
    private List<T> sourceDatas = new ArrayList<>();
    private int mLayoutId;

    /**
     * @param context  上下文
     * @param sourceDatas 数据集
     * @param layoutId 布局ID
     */
    public AbsListAdapter(Context context, List<T> sourceDatas, int layoutId) {
        this.mContext = context;
        this.mLayoutId = layoutId;
        if (sourceDatas != null) {
            this.sourceDatas = sourceDatas;
        }
    }

    public void addDatas(List<T> datas) {
        this.sourceDatas.addAll(datas);
        notifyDataSetChanged();
    }

    public void clearDatas() {
        this.sourceDatas.clear();
        notifyDataSetChanged();
    }

    public T getDataById(int position) {
        return sourceDatas.get(position);
    }

    @Override
    public int getCount() {
        return sourceDatas.size();
    }

    @Override
    public T getItem(int position) {
        return sourceDatas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //实例化一个ViewHolder
        ViewHolder holder = ViewHolder.getInstance(mContext, convertView, parent, mLayoutId, position);
        //需要自定义的部分
        convert(position, holder, getItem(position));
        return holder.getConvertView();
    }

    /**
     * 需要处理的部分，在这里给View设置值
     *
     * @param holder ViewHolder
     * @param bean   数据集
     */
    public abstract void convert(int position, ViewHolder holder, T bean);
}